#!/bin/bash

export PATH=$PATH:/usr/local/bin
ROOT_PATH=$(pwd)
ip_pattern='([0-9]{1,3}\.){3}[0-9]{1,3}'
password_pattern='[0-9a-zA-Z_]{6,}'
port_pattern='[0-9]{1,5}'

tmux_install() {
    line_separator "Install Tmux ..." t
    rpm -q tmux &> /dev/null
    local res_a="$?"
    which tmux &> /dev/null
    local res_b="$?"

    if [ ! "$res_a" -eq 0 -a ! "$res_b" -eq 0 ];then
        yum_install gcc libevent-devel ncurses-devel automake bison
        cd sources
        tar -zxf tmux-2.6.tar.gz
        cd tmux-2.6
        ./autogen.sh && ./configure && make && make install
        cd ..
        rm tmux-2.6 -rf
        cd ..
    else
        line_separator "tmux installed,nothing to deal with."
    fi
}

docker_install() {
    line_separator "Install Docker ..." d
    rpm_install docker "http://mirrors.aliyun.com/docker-ce/linux/centos/7/x86_64/stable/Packages" "docker-ce-18.03.1.ce-1.el7.centos.x86_64.rpm"
    if [ "$?" -eq 0 ]; then
        test -d /etc/docker || mkdir -p /etc/docker
        cat > /etc/docker/daemon.json << EOF
{
  "registry-mirrors": ["http://hub-mirror.c.163.com","https://docker.mirrors.ustc.edu.cn"]
}
EOF
        systemctl enable docker.service
        systemctl start docker.service
    fi
}

mysql_install() {
    line_separator "Install MySQL ..." m
    # mysql 官方网址下载太慢,切换为本地 rpm 包安装方式
    # rpm_install mysql "http://dev.mysql.com/get" "mysql57-community-release-el7-10.noarch.rpm" "mysql-community-server"
    check_package_exists mysql centos
    if [ "$?" -eq 0 ]; then
        yum_install libaio
        yum_remove mariadb postfix
        rpm_file_install "https://mirrors.163.com/mysql/Downloads/MySQL-5.7" \
            "mysql-community-common-5.7.28-1.el7.x86_64.rpm" \
            "mysql-community-libs-5.7.28-1.el7.x86_64.rpm" \
            "mysql-community-libs-compat-5.7.28-1.el7.x86_64.rpm" \
            "mysql-community-client-5.7.28-1.el7.x86_64.rpm" \
            "mysql-community-server-5.7.28-1.el7.x86_64.rpm"

        read_from_stdin "please enter mysql port(default 3306): " mysql_port "port is not correct,please enter again." $port_pattern
        read_from_stdin "please enter mysql root password(default uniqueStudy2018): " mysql_root_password \
            "password is not correct,please enter again." $password_pattern
        mysql_port=${mysql_port:-3306}
        mysql_root_password=${mysql_root_password:-uniqueStudy2018}
        cat > /etc/my.cnf << EOF
[client]
default-character-set=utf8


[mysqld]
character-set-server=utf8
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

port=$mysql_port
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock

symbolic-links=0

log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid


[mysql]
default-character-set=utf8
EOF
        line_separator "mysql boot up port: $mysql_port"
        systemctl enable mysqld.service
        systemctl start mysqld.service
        sleep 1
        local initial_password=$(cat /var/log/mysqld.log | egrep '^.*password.*root@localhost:\s*(\S+)$' \
            | sed 's/^.*password.*root@localhost:\s*\(\S\+\)$/\1/g')
        if [ x != x"$initial_password" ]; then
            mysql -uroot -p"$initial_password" -P$mysql_port mysql -t --connect-expired-password \
                -e "set global validate_password_policy=LOW;" \
                -e "set global validate_password_length=4;" \
                -e "alter user 'root'@'localhost' identified by '$mysql_root_password';" \
                -e "update user set host='%' where user='root';" \
                -e "grant all privileges on *.* to 'root'@'%' identified by '$mysql_root_password' with grant option;" \
                -e "flush privileges;" &> /dev/null
            line_separator "mysql root password: $mysql_root_password"
        else
            line_separator "retrieve mysql root initial password failed,please check. /var/log/mysqld.log"
        fi
    fi
}

set_static_ip() {
    line_separator "Set Up Network Cards ..." i
	local eth_names=$(ifconfig | egrep "^e" | awk -F ':' '{print $1}' | uniq)
    for eth_name in $eth_names
    do
        line_separator "$eth_name"
        read_from_stdin "please enter ipaddr(default empty not set): " ipaddr "ipaddr is not correct,please enter again." $ip_pattern
        read_from_stdin "please enter gateway(default empty not set): " gateway "gateway is not correct,please enter again." $ip_pattern
        read_from_stdin "please enter netmask(default empty not set): " netmask "netmask is not correct,please enter again." $ip_pattern
        read_from_stdin "please enter dns(default empty not set): " dns "dns is not correct,please enter again." $ip_pattern
        if [ x"$ipaddr" = x -o x"$gateway" = x -o x"$netmask" = x -o x"$dns" = x ]; then
            line_separator "jump card $eth_name,using default settings.\n"
        else
            local uuid_line=$(cat /etc/sysconfig/network-scripts/ifcfg-"$eth_name" | egrep '^UUID=.*$')
            cat > /etc/sysconfig/network-scripts/ifcfg-"$eth_name" << EOF
TYPE="Ethernet"
NAME="$eth_name"
DEVICE="$eth_name"
BOOTPROTO="static"
DEFROUTE="yes"
PEERDNS="yes"
PEERROUTES="yes"
IPV4_FAILURE_FATAL="no"
IPV6INIT="yes"
IPV6_AUTOCONF="yes"
IPV6_DEFROUTE="yes"
IPV6_PEERDNS="yes"
IPV6_PEERROUTES="yes"
IPV6_FAILURE_FATAL="no"
IPV6_ADDR_GEN_MODE="stable-privacy"
ONBOOT="yes"
IPADDR="$ipaddr"
NETMASK="$netmask"
GATEWAY="$gateway"
DNS1="$dns"
DNS2="114.114.114.114"
$uuid_line
EOF
            cat > /etc/resolv.conf << EOF
nameserver $dns
nameserver 114.114.114.114
EOF
            line_separator "card $eth_name set up successfully.\n"
        fi
    done
    systemctl restart network.service
}

aliyun_repo() {
    line_separator "Set Up Aliyun Repo ...\n"
    mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.bak
    cp CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo
    yum clean all
    yum makecache
    # 更新 xfsprogs 版本,解决 docker 启动报错问题
    yum update xfsprogs -y
}

stop_fire_wall() {
    line_separator "Disable FireWall ..." f
    systemctl stop firewalld.service
    systemctl disable firewalld.service
}

stop_selinux() {
    line_separator "Disable Selinux ..." s
    setenforce 0
    sed -in 's/^SELINUX\s*=\s*enforcing\s*$/SELINUX=disabled/g' /etc/selinux/config
}

stop_networkmanager() {
    line_separator "Disable NetworkManager ..." n
    systemctl stop NetworkManager.service
    systemctl disable NetworkManager.service
}

restart_sshd() {
    line_separator "Restart SSHD Service ..." s
    read_from_stdin "please enter sshd port(default 22): " sshd_port "port is not correct,please enter again." $port_pattern
    sshd_port=${sshd_port:-22}
    cat > /etc/ssh/sshd_config << EOF
Port $sshd_port

HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key

SyslogFacility AUTHPRIV

PermitRootLogin yes

PubkeyAuthentication yes

AuthorizedKeysFile .ssh/authorized_keys

PasswordAuthentication no

ChallengeResponseAuthentication no

GSSAPIAuthentication no
GSSAPICleanupCredentials no

UsePAM yes

X11Forwarding yes
UsePrivilegeSeparation sandbox		# Default for new installations.
UseDNS no

AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv XMODIFIERS

Subsystem sftp	/usr/libexec/openssh/sftp-server
EOF
    systemctl restart sshd.service
}

exec_cmds() {
    aliyun_repo
    yum_install which vim tmux ctags cscope gawk sudo net-tools wget curl zip unzip cjkuni-ukai-fonts kde-l10n-Chinese
    stop_fire_wall
    stop_selinux
    stop_networkmanager
    set_static_ip
    restart_sshd
    docker_install
    mysql_install
    tmux_install
    config_file
    config_vim
    config_ssh
    reboot_server
}

source lib/common.sh

${1-exec_cmds}
